package com.ths.inputservice.ui;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.SPUtils;
import com.ths.inputservice.R;
import com.ths.inputservice.video.RtspPlayerManager;

import org.videolan.libvlc.LibVLC;
import org.videolan.libvlc.util.VLCVideoLayout;

public class MainActivity extends AppCompatActivity {

    private VLCVideoLayout surfaceBig;
    private VLCVideoLayout surfaceSmall;
    private ImageButton btnPlay;
    private ImageView btnSwap;
    private ImageButton btnWindowSwitch;
    private ImageView btnSettings;
    private ImageButton btnRecord;

    private FrameLayout mainContainer; // 主容器
    private FrameLayout bigWindowContainer; // 大窗口容器
    private FrameLayout smallWindowContainer; // 小窗口容器

    // 窗口大小状态，true表示小窗口放大模式
    private boolean isSmallWindowEnlarged = false;

    private RtspPlayerManager playerBig;
    private RtspPlayerManager playerSmall;

    private boolean isPlaying = false;
    private boolean swapped = false;
    private final Handler handler = new Handler(Looper.getMainLooper());

    private SettingsPopupManager settingsPopupManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 保存主容器引用
        mainContainer = findViewById(R.id.main);

        // 初始化控件
        surfaceBig = findViewById(R.id.surface_big);
        surfaceSmall = findViewById(R.id.surface_small);
        bigWindowContainer = (FrameLayout) surfaceBig.getParent();
        smallWindowContainer = (FrameLayout) surfaceSmall.getParent();
        btnPlay = findViewById(R.id.btn_play);
        btnSwap = findViewById(R.id.btn_swap);
        btnWindowSwitch = findViewById(R.id.btn_window_switch);
        btnSettings = findViewById(R.id.btn_settings);
        btnRecord = findViewById(R.id.btn_record);

        // 初始化播放器，指定名称以区分不同播放器的重连状态
        playerBig = new RtspPlayerManager(this, surfaceBig, "big");
        playerSmall = new RtspPlayerManager(this, surfaceSmall, "small");

        // 初始化设置弹窗管理器
        settingsPopupManager = new SettingsPopupManager(this);
        settingsPopupManager.setOnSettingsSavedListener(new SettingsPopupManager.OnSettingsSavedListener() {
            @Override
            public void onSettingsSaved(String url1, String url2) {
                Toast.makeText(getApplicationContext(), "设置已保存", Toast.LENGTH_SHORT).show();
                // 重新加载播放器
                if (isPlaying) {
                    restartPlayers();
                }
            }

            @Override
            public void onCheckedSwitch(Boolean b) {
                if (b) {
                    surfaceSmall.setVisibility(View.VISIBLE);
                } else {
                    surfaceSmall.setVisibility(View.GONE);
                }
            }

            @Override
            public void onCloseWindow(String url1, String url2) {
//                if (isPlaying) {
//                    restartPlayers();
//                }
            }

            @Override
            public void onPopupOpened() {
//                if (isPlaying) {
//                    new Handler(Looper.getMainLooper()).postDelayed(() -> stopPlayers(), 200);
//                }
            }
        });
        boolean showWindow = SPUtils.getInstance().getBoolean("ShowWindow", true);
        if (showWindow) {
            surfaceSmall.setVisibility(View.VISIBLE);
        } else {
            surfaceSmall.setVisibility(View.GONE);
        }
        // 设置按钮点击事件
        setupButtonListeners();

    }

    /**
     * 设置所有按钮的点击事件
     */
    private void setupButtonListeners() {
        btnPlay.setOnClickListener(v -> {
            if (isPlaying) {
                stopPlayers();
            } else {
                startPlayers();
            }
        });

        btnSwap.setOnClickListener(v -> swapWindows());
        btnWindowSwitch.setOnClickListener(v -> switchWindowMode());
        btnSettings.setOnClickListener(v -> {
            settingsPopupManager.showSettingsPopup(v);
        });
        btnRecord.setOnClickListener(v -> {
            if (playerBig.isRecording()) {
                playerBig.stopRecording();
                playerSmall.stopRecording();
            } else {
                playerBig.startRecording(getExternalFilesDir(null));
                playerSmall.startRecording(getExternalFilesDir(null));
            }
        });

        // VLCVideoLayout 直接由 MediaPlayer.attachViews 管理，无需 Surface 回调
    }

    private void startPlayers() {
        String[] urls = readUrls();

        // 检查URL是否有效，只有有效URL才播放
        if (urls[0] != null && !urls[0].isEmpty()) {
            playerBig.play(urls[0]);
        }

        if (urls[1] != null && !urls[1].isEmpty()) {
            playerSmall.play(urls[1]);
        }

        // 只有当至少有一个有效URL时才更新播放状态
        if ((urls[0] != null && !urls[0].isEmpty()) || (urls[1] != null && !urls[1].isEmpty())) {
            isPlaying = true;
            btnPlay.setImageResource(android.R.drawable.ic_media_pause);
        } else {
            // 如果没有有效URL，则保持停止状态
            isPlaying = false;
            btnPlay.setImageResource(android.R.drawable.ic_media_play);
        }
    }

    private void stopPlayers() {
        playerBig.stop();
        playerSmall.stop();
        isPlaying = false;
        btnPlay.setImageResource(android.R.drawable.ic_media_play);
    }

    private void swapWindows() {
        if (!swapped) {
            playerBig.attachSurface(surfaceSmall);
            playerSmall.attachSurface(surfaceBig);
        } else {
            playerBig.attachSurface(surfaceBig);
            playerSmall.attachSurface(surfaceSmall);
        }
        swapped = !swapped;
        // 小窗与控制条始终置顶
        findViewById(R.id.surface_small).bringToFront();
        findViewById(R.id.controls).bringToFront();
    }

    /**
     * 切换大小窗口模式 - 实际上只是切换两个窗口的播放地址
     */
    private void switchWindowMode() {
        // 暂停当前播放，避免切换过程中花屏
        boolean wasPlaying = isPlaying;
        if (wasPlaying) {
            stopPlayers();
        }

        // 获取当前的播放地址
        String[] urls = readUrls();
        String tempUrl = urls[0];
        urls[0] = urls[1];
        urls[1] = tempUrl;

        // 延迟一点时间重新开始播放，确保切换平滑
        if (wasPlaying) {
            handler.postDelayed(() -> {
                // 使用交换后的地址播放
                if (urls[0] != null && !urls[0].isEmpty()) {
                    playerBig.play(urls[0]);
                }

                if (urls[1] != null && !urls[1].isEmpty()) {
                    playerSmall.play(urls[1]);
                }

                // 更新播放状态
                if ((urls[0] != null && !urls[0].isEmpty()) || (urls[1] != null && !urls[1].isEmpty())) {
                    isPlaying = true;
                    btnPlay.setImageResource(android.R.drawable.ic_media_pause);
                }
            }, 300);
        }
    }

    private String[] readUrls() {
        SharedPreferences sp = getSharedPreferences("rtsp", Context.MODE_PRIVATE);
        String u1 = sp.getString("url1", "rtsp://192.168.144.25:8554/main.264");
        String u2 = sp.getString("url2", "rtsp://192.168.144.26:8554/main.264");

        // 检查是否为"关闭"
        if ("关闭".equals(u1)) {
            u1 = "";
        }
        if ("关闭".equals(u2)) {
            u2 = "";
        }

        return new String[]{u1, u2};
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        playerBig.release();
        playerSmall.release();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 在应用进入后台时完全停止播放，避免后台返回时花屏
        if (isPlaying) {
            playerBig.stop();
            playerSmall.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        enterImmersive();
        // 从后台返回时，先停止所有播放，然后重新开始播放
        if (isPlaying) {
            swapWindows();
            restartPlayers();
        }
    }

    // 为设置弹窗暂停播放
    public void pausePlayersForSettings() {
        if (isPlaying) {
            // 只暂停播放，不改变状态标志
            playerBig.stop();
            playerSmall.stop();
        }
    }

    // 重新加载播放地址
    private void restartPlayers() {
        stopPlayers();
        startPlayers();
    }

    private void enterImmersive() {
        View decor = getWindow().getDecorView();
        int flags = View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN;
        decor.setSystemUiVisibility(flags);
    }
}


